package cz.cuni.mff.ufal.volkapp;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Scanner;

import org.apache.log4j.Logger;

import cz.cuni.mff.ufal.volk.Component;
import cz.cuni.mff.ufal.volk.Listener;

public class UserTextInput implements Component, Runnable {

	private final static Logger log = Logger.getLogger(UserTextInput.class);
	private final Thread thread = new Thread(this);
	private final Scanner in = new Scanner(System.in);
	private final String exitCommand;
	private final List<Listener<String>> listeners;

	public UserTextInput(String exitCommand, List<Listener<String>> listeners) {
		this.exitCommand = exitCommand;
		this.listeners = new ArrayList<Listener<String>>(listeners);
	}

	@Override
  public void open() throws IOException {
		log.trace("open()");
		thread.start();
  }

	@Override
  public void close() throws IOException {
		log.trace(">> close()");
	  System.in.close();
    log.trace("<< close()");
  }

	@Override
  public void run() {
		try {
			String next;
			while ((next = in.nextLine()) != null) {
				log.info("command received: " + next);
				if (next.equals(exitCommand)) {
					break;
				} else {
					for (Listener<String> listener : listeners) {
						try {
							listener.process(next);
						} catch (Exception e) {
							log.error("An unexpected error occurred when processing text input", e);
						}
					}
				}
			}
		} catch (NoSuchElementException e) {
			log.warn("The input stream has been unexpectadly closed", e);
		}
		Application.getApplication().close();
  }

}
